import { hash } from 'ohash'

// 后端返回的数据类型
export interface ResOptions<T> {
  data: T
  code?: number
  message?: string
  elapsed: number
}

/**
 * api请求封装
 * @param { String } url 请求地址
 * @param { Object } options useFtech第二个参数
 * @param { Object } headers 自定义header头, 单独设置headers区分请求参数，也好设置类型
 */
const fetch = async (
  url: string,
  options?: any,
  headers?: any,
  isNeedToken = false,
) => {
  try {
    // 3.0正式版环境变量要从useRuntimeConfig里的public拿
    const {
      public: { baseUrl },
    } = useRuntimeConfig()
    // console.log('baseUrl', baseUrl)
    if (!baseUrl) {
      throw new Error('baseUrl is undefined')
    }

    // 根据环境选择请求URL
    // const reqUrl =
    //   process.env.NODE_ENV === 'development' ? `/api${url}` : `${baseUrl}${url}`
    const reqUrl = `/api${url}`

    // 设置key
    const key = hash(JSON.stringify(options) + url)

    // 可以设置默认headers例如，token的获取最好用useState返回一个useCookie
    // const customHeaders = { token: useToken().value, ...headers }

    var customHeaders = {}
    if (isNeedToken) {
      customHeaders = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'ACCESS-TOKEN': localStorage.getItem('access_token') || '',
        'x-access-token': localStorage.getItem('access_token'),
        ...headers,
      }
    } else {
      customHeaders = {
        'Content-Type': 'application/x-www-form-urlencoded',
        ...headers,
      }
    }
    const { data, error } = await useFetch(reqUrl, {
      ...options,
      key,
      headers: customHeaders,
      withCredentials: true,
      credentials: 'include',
    })
    const result = data.value as ResOptions<any>
    if (error.value || !result || (result && result.code !== 0)) {
      // 处理token失效的情况
      if (result?.code && result.code === -10) {
        await navigateTo('/')
      }
    }
    return result // 这里直接返回data或者其他的
  } catch (err) {
    console.error(err)
    return Promise.reject(err)
  }
}

export default class Http {
  get(url: string, params?: any, headers?: any) {
    return fetch(url, { method: 'get', params }, headers)
  }

  post(url: string, body?: any, headers?: any, isNeedToken = false) {
    return fetch(url, { method: 'post', body }, headers, isNeedToken)
  }

  put(url: string, body?: any, headers?: any) {
    return fetch(url, { method: 'put', body }, headers)
  }

  delete(url: string, body?: any, headers?: any) {
    return fetch(url, { method: 'delete', body }, headers)
  }
}
